package com.cms.crash.handler

import android.annotation.SuppressLint
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.utils.ToastUtils
import com.cms.crash.R
import com.cms.crash.databinding.ActivityCrashBinding
import com.cms.crash.handler.CustomActivityOnCrash.*
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.*

/**
 * crash页面
 */
class CrashActivity: BaseActivity<ActivityCrashBinding>() {
    private var filePath =""
    private var erroInfo = ""
     fun initData() {
        filePath = cacheDir.absolutePath+"/crash/log/"
        getStackTraceFromIntent(this@CrashActivity.intent)?.let {
            mBinding.tvcontents.text = it
            erroInfo = it
            saveExceptionFile(it,filePath)
        }
        mBinding.run {
            val config = getConfigFromIntent(this@CrashActivity.intent)
            errorRestart.setOnClickListener {
                config?.run {
                    restartApplication(this@CrashActivity, this)
                }
            }
            errorSendError.setOnClickListener {
                   // saveExceptionFile(erroInfo,filePath)
                finish()

            }
        }
    }
    /**
     * 保存异常信息到SD卡
     */
    @SuppressLint("SimpleDateFormat")
    private fun saveExceptionFile(exception: String, filePath: String) {
        val dir = File(filePath)
        if (!dir.exists()) dir.mkdirs()
        val format = SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Date())
        val file = File("$filePath$format-crash-log.text")
        try {
            val printWriter = PrintWriter(BufferedWriter(FileWriter(file)))
            printWriter.write(exception)
            printWriter.close()
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
        ToastUtils.show(this@CrashActivity,"日志保存成功!")
    }

    override fun getLayoutId(): Int = R.layout.activity_crash

    override fun initView() {
      initData()
    }

    override fun initListener() {

    }
}